package com.${artifactId}.config;

import ch.qos.logback.ext.spring.web.LogbackConfigListener;
import com.fow.core.platform.web.filter.PlatformFilter;
import org.springframework.core.annotation.Order;
import org.springframework.web.WebApplicationInitializer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Created by Greg.Chen on 2015/5/28.
 */
@Order(1)
public class WebInitializer implements WebApplicationInitializer {

    private static final String ENV_KEY = "runtime.env";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        InputStream in = getClass().getClassLoader().getResourceAsStream("runtime.properties");
        Properties prop = new Properties();
        try {
            prop.load(in);
        } catch (IOException e) {
            throw new ServletException(e);
        }
        finally {
            try {
                in.close();
            } catch (IOException e) {
                throw new ServletException(e);
            }
        }
        String env = prop.getProperty(ENV_KEY);
        System.setProperty(ENV_KEY, env);


        servletContext.setInitParameter("logbackConfigLocation", String.format("classpath:conf/%s/logback.xml", env));
        servletContext.addListener(LogbackConfigListener.class);

        servletContext.setInitParameter("webAppRootKey","${artifactId}");

        servletContext.addFilter("platformFilter", PlatformFilter.class).addMappingForUrlPatterns(null,false, "/*");
    }
}
